package top.ibase4j.core.support.context;

import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;

/**
 * @author ShenHuaJie
 * @since 2019年4月4日 下午3:00:15
 */
@SuppressWarnings("unchecked")
public class DubboContext {
    private static ApplicationConfig dubboApplication;
    private static RegistryConfig dubboRegistry;

    public static <T> T getService(Class<T> cls) {
        if (dubboApplication == null || dubboRegistry == null) {
            synchronized (DubboContext.class) {
                if (dubboApplication == null) {
                    dubboApplication = ApplicationContextHolder.getBean(ApplicationConfig.class);
                }
                if (dubboRegistry == null) {
                    dubboRegistry = ApplicationContextHolder.getBean(RegistryConfig.class);
                }
            }
        }
        // 引用远程服务
        ReferenceConfig<?> reference = new ReferenceConfig<>();
        reference.setApplication(dubboApplication);
        reference.setRegistry(dubboRegistry); // 多个注册中心可以用setRegistries()
        reference.setCheck(false);
        reference.setInterface(cls);
        return (T)reference.get();
    }
}
